<template>
  <div class="component">
    <el-card shadow="never" :body-style="{ padding: '0px' }">
      <el-form ref="form" :model="form" :rules="rules">
        <h1 class="title">注册</h1>

        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            @focus="inputFocus(0)"
            v-model="form.username"
            placeholder="请输入用户名"
            clearable
          >
            <template #prefix>
              <svg-icon
                :class="iconClass[0].class"
                class="icon"
                iconClass="user"
              ></svg-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item prop="email">
          <el-input
            @focus="inputFocus(1)"
            v-model="form.email"
            placeholder="请输入邮箱地址"
            clearable
          >
            <template #prefix>
              <svg-icon
                :class="iconClass[1].class"
                class="icon"
                iconClass="message"
              ></svg-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            type="password"
            @focus="inputFocus(2)"
            v-model="form.password"
            placeholder="请输入密码"
            clearable
          >
            <template #prefix>
              <svg-icon
                :class="iconClass[2].class"
                class="icon"
                iconClass="lock"
              ></svg-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="rePassword">
          <el-input
            type="password"
            @focus="inputFocus(3)"
            v-model="rePassword"
            placeholder="请确认密码"
            clearable
          >
            <template #prefix>
              <svg-icon
                :class="iconClass[3].class"
                class="icon"
                iconClass="unLock"
              ></svg-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item>
          <el-row :gutter="10">
            <el-col :span="14">
              <el-form-item prop="verify">
                <el-input
                  v-model="form.captcha"
                  @focus="inputFocus(4)"
                  placeholder="输入图片验证码"
                  clearable
                >
                  <template #prefix>
                    <svg-icon
                      :class="iconClass[4].class"
                      class="icon"
                      iconClass="picture"
                    ></svg-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <a @click="loadVerifyImg" href="javascript:;">
                <el-image
                  :src="captcha"
                  fit="contain"
                  v-loading="loading.verify"
                >
                  <template #error>
                    <span class="error-verify"> 验证码请求失败 </span>
                  </template>
                </el-image>
              </a>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item class="btn">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-button @click="toRegister" type="primary">注册</el-button>
            </el-col>
            <el-col :span="12">
              <el-button @click="reset('form')">重置</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { captcha, login, register } from "@/api/auth";
import { Message } from "element-ui";

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (this.rePassword === "") {
        callback(new Error("请再次输入密码"));
      } else if (this.rePassword !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // 控制loading
      loading: {
        verify: false,
        fullScreen: undefined,
      },

      // 表单数据
      form: {
        username: "",
        email: "",
        password: "",
        captcha: "",
        captchaId: undefined,
      },

      captcha: undefined,
      rePassword: "",

      //控制icon颜色变换
      iconClass: [
        {
          type: 0,
          class: "",
        },
        {
          type: 1,
          class: "",
        },
        {
          type: 2,
          class: "",
        },
        {
          type: 3,
          class: "",
        },
        {
          type: 4,
          class: "",
        },
      ],

      // 校验规则
      rules: {
        username: [
          {
            required: true,
            message: "用户名不能为空！",
            trigger: "blur",
          },
          {
            min: 3,
            max: 16,
            message: "用户名长度为3到16个字符！",
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱不能为空！",
            trigger: "blur",
          },
          {
            pattern: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/,
            message: "邮箱格式错误！",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空！",
            trigger: "blur",
          },
          {
            min: 8,
            max: 64,
            message: "用户名长度为8到64个字符！",
          },
        ],
        rePassword: [{ validator: validatePass, trigger: "blur" }],
        captcha: [
          {
            required: true,
            message: "验证码不能为空！",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.loadVerifyImg();
  },
  methods: {
    // 登录按钮点击事件
    toRegister() {
      this.loading.fullScreen = this.$loading(
        this.$store.state.fullScreeLoadingOption
      );

      register(this.form).then((res) => {
        this.loading.fullScreen.close();
        if (res !== null) {
          Message({
            message: "注册成功",
            type: "success",
            duration: 5 * 1000,
          });
        } else {
          Message({
            message: res.msg || "注册失败",
            type: "error",
            duration: 5 * 1000,
          });
        }

        // 登录
        const username = this.form.username;
        const password = this.form.password;
        const captcha = this.form.captcha;
        const captchaId = this.form.captchaId;
        login({ username, password, captcha, captchaId })
          .then((res) => {
            this.$store.dispatch("user/setUserInfo", res);
            this.loading.fullScreen.close();
            this.$router.push("/pageFork");
          })
          .catch(() => {
            this.loading.fullScreen.close();
          });
      }).catch(error => {
        console.log(error);
        this.loading.fullScreen.close();
      });


      // add("user", this.form)
      //   .then((res) => {
      //     this.loading.fullScreen.close();
      //     if (res !== null) {
      //       Message({
      //         message: "注册成功",
      //         type: "success",
      //         duration: 5 * 1000,
      //       });
      //     } else {
      //       Message({
      //         message: res.msg || "注册失败",
      //         type: "error",
      //         duration: 5 * 1000,
      //       });
      //     }

      //     //注册后登录
      //     this.$store
      //       .dispatch("user/login", this.form)
      //       .then(() => {
      //         this.loading.fullScreen.close();
      //         this.$router.push("/pageFork");
      //       })
      //       .catch(() => {
      //         this.loading.fullScreen.close();
      //       });
      //   })
      //   .catch((error) => {
      //     // 关闭加载中动画
      //     console.log(error);
      //     this.loading.fullScreen.close();
      //   });
    },

    // 重置按钮点击事件
    reset(formName) {
      this.$refs[formName].resetFields();
      this.iconClass.forEach((element) => {
        element.class = "";
      });
    },

    // 输入框获得焦点事件
    inputFocus(type) {
      this.iconClass.forEach((element) => {
        if (element.type === type) {
          element.class = "active";
        } else {
          element.class = "";
        }
      });
    },

    // 获取验证码
    loadVerifyImg() {
      this.loading.verify = true;

      const captchaId = this.form.captchaId;

      captcha({ captchaId })
        .then((data) => {
          this.captcha = "data:image/jpg;base64," + data.img;
          this.form.captchaId = data.captchaId;
          this.loading.verify = false;
        })
        .catch((error) => {
          console.log(error);
          this.loading.verify = false;
        });
    },
  },
};
</script>

<style lang='scss' scoped>
$color-icon-active: #909399;
$color-bg: #f5f7fa;
$color-bg-gray: #e9e9eb;
$color-error: #f56c6c;
$boder-radius: 4px;

.component {
  .el-card {
    width: 100%;
    border: none;
    background-color: $color-bg;

    .el-form {
      text-align: left;

      .el-input {
        width: 100%;
        .icon {
          width: 1.5rem;
          &.active {
            color: $color-icon-active;
          }
        }
      }

      .title {
        padding-bottom: 2rem;
      }

      .el-image {
        width: 100%;
        background-color: $color-bg-gray;
        border-radius: $boder-radius;
        text-align: center;

        .error-verify {
          color: $color-error;
          text-decoration: none;
        }
      }

      .btn {
        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>